<?php
class Category extends CActiveRecord{
	
	public static function model($className = __CLASS__){
		return parent::model($className);
	}
	
	public function tableName(){
		return '{{category}}';
	}
	
	public function attributeLabels(){
		return array(
				'pid'=>'所属栏目',
				'title'=>'文章标题',
				'name'=>'标识',
				'template'=>'模版',
				'sort'=>'排序',
				'keywords'=>'关键字',
				'description'=>'描述'
		);
	}
	
	/**
	 * 验证规则
	 * @see CModel::rules()
	 */
	public function rules(){
		return array(
				array('pid', 'numerical', 'message'=>'请选择正确的栏目'),
				array('title', 'required', 'message'=>'栏目标题不能为空'),
				array('name', 'match', 'pattern'=>'/[a-z]+/', 'message'=>'唯一标识为英文字符'),
				array('template', 'safe'),
				array('sort', 'numerical', 'message'=>'排序必须为数字'),
				array('keywords,description', 'filter', 'filter'=>'strip_tags')
		);
	}
	
	/**
	 * 获取无限极栏目树
	 * @param string $dorpDownlist 	是否需要组合成yii识别的下拉框组件
	 * @param string $addTop 是否需要添加顶级栏目
	 * @return Ambigous <multitype:string , multitype:, multitype:unknown >
	 */
	public function cateTree($dorpDownlist = true, $addTop = true){
		$sql = "SELECT * FROM {{category}}";
		$obj = Yii::app()->db->createCommand($sql);
		$cateArr = $obj->queryAll();
		$cateTree = $this->getCateTree($cateArr);
		return $dorpDownlist ? $this->toDropdown($cateTree, $addTop) : $cateTree;
	}
	
	/**
	 * 组合无限极栏目
	 * @param array $cateArr 数组
	 */
	public function getCateTree($cateArr, $pid = 0, $level = 0){
		$newArr = array();
		if(!is_array($cateArr)){
			return array();
		}
		foreach($cateArr as $v){
			if($v['pid'] == $pid){
				$v['html'] = str_repeat("　", $level);
				$newArr[] = $v;
				$newArr = array_merge($newArr, self::getCateTree($cateArr, $v['category_id'], $level+1));
			}
		}
		return $newArr;
	}
	
	/**
	 * 拼接字符串为yii dropdownlist识别数组
	 * @param array $cateTree 带无限极分类的数组
	 * @return multitype:string 
	 */
	private function toDropdown($cateTree, $addTop = true){
		$arr = $addTop ? array('==顶级栏目==') : array();
		foreach($cateTree as $v){
			$arr[$v['category_id']] = $v['html'] . '|—'.$v['title'];
		}
		return $arr;
	}
	
	/**
	 * 通过栏目唯一标识获取栏目ID号及子栏目
	 * @param unknown $name
	 */
	public function getCids($name){
		$cids = array();
		$res = $this->findByAttributes(array('name'=>$name));
		if(!empty($res->category_id)){
			$sql = "SELECT category_id,pid,name,title FROM {{category}}";
			$list = Yii::app()->db->createCommand($sql)->queryAll();
			$cidArr = self::getChilds($list, $res->category_id);
			
			foreach($cidArr as $v){
				$cids[] = $v['category_id'];
			}
			
			//把自己加上
			array_unshift($cids, $res->category_id);
		}
		return implode(',',$cids);
	}
	
	/**
	 * 子栏目ID
	 * @param unknown $cid
	 * @return array 子栏目数组
	 */
	protected static function getChilds($list, $cid){
		static $cidArr = array();
		foreach($list as $v){
			if($v['pid'] == $cid){
				$cidArr[] = $v;
				self::getChilds($list, $v['category_id']);
			}
		}
		return $cidArr;
	}
}